package com.atguigu.test1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadMes2 {
    public static void main(String[] args) {
        Source2 source = new Source2();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(100);
                    source.increment1();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(100);
                    source.increment2();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(100);
                    source.decrement3();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
}


// V1 synchronized + wait + notifyAll 传统老版本
class Source2 {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void increment1() throws InterruptedException {  //加1
        lock.lock();
        try {
           while (number != 0) condition1.await();
            System.out.print(Thread.currentThread().getName());
            System.out.println(" 加一之后: " + (++number));
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }
    public void increment2() throws InterruptedException {  //加2
        lock.lock();
        try {
           while (number != 1) condition2.await();
            System.out.print(Thread.currentThread().getName());
            number += 2;
            System.out.println(" 加二之后: " + number);
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }
    public void decrement3() throws InterruptedException {  //减3
        lock.lock();
        try {
            while (number != 3) condition3.await();
            System.out.print(Thread.currentThread().getName());
            number -= 3;
            System.out.println(" 减三之后: " + number);
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }
}
